﻿using DotNetty.Buffers;
using DotNetty.Common.Utilities;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using System;
using System.Text;

namespace EchoServer
{
    /// <summary>
    /// 因为服务器只需要响应传入的消息，所以只需要实现ChannelHandlerAdapter就可以了
    /// </summary>
    public class EchoServerHandler : ChannelHandlerAdapter
    {
        /// <summary>
        /// 每个传入消息都会调用
        /// 处理传入的消息需要复写这个方法
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="msg"></param>
        public override void ChannelRead(IChannelHandlerContext ctx, object msg)
        {
            IByteBuffer message = msg as IByteBuffer;
            //// 检查是否有支撑数组
            //if (message.HasArray)
            //{
            //    // 获取数组
            //    byte[] array = message.Array;
            //    // 计算第一个字节的偏移
            //    int offset = message.ArrayOffset + message.ReaderIndex;
            //    // 获取可读字节数
            //    int length = message.ReadableBytes;
            //    // 调用方法，处理数据
            //    HandleArray(array, offset, length);
            //}
            //if (message.HasArray)
            //{
            //    int length = message.ReadableBytes;
            //    byte[] array = new byte[length];
            //    message.GetBytes(message.ReaderIndex, array);
            //    HandleArray(array, 0, length);
            //}
            // 创建一个复合缓冲区
            //CompositeByteBuffer messageBuf = Unpooled.CompositeBuffer();
            // 创建两个ByteBuffer
            //IByteBuffer headBuf = Unpooled.CopiedBuffer(message);
            //IByteBuffer bodyBuf = Unpooled.CopiedBuffer(message);
            //// 添加到符合缓冲区中
            //messageBuf.AddComponents(headBuf, bodyBuf);
            //// 删除
            //messageBuf.RemoveComponent(0);
            //for (int i = 0; i < message.Capacity; i++)
            //{
            //    // 如此使用索引访问不会改变读索引也不会改变写索引
            //    byte b = message.GetByte(i);
            //    Console.WriteLine(b);
            //}
            //message.DiscardReadBytes();
            //while (message.IsReadable())
            //{
            //    Console.WriteLine(message.ReadByte());
            //}
            //Console.WriteLine("收到信息：" + message.ToString(Encoding.UTF8));
            // 使用随机数填充可写区域
            //while (message.WritableBytes > 4)
            //{
            //    message.WriteInt(new Random().Next(0, 100));
            //}
            //ctx.Channel.EventLoop.Schedule(() =>
            //{
            //    Console.WriteLine("delay 1s");
            //}, new TimeSpan(1000));

            //var bootstrap = new Bootstrap();
            //bootstrap.Group(ctx.Channel.EventLoop);
            //bootstrap.Channel<TcpServerSocketChannel>();
            //bootstrap.ChildHandler(new ActionChannelInitializer<IChannel>(channel =>
            //{
            //    IChannelPipeline pipeline = channel.Pipeline;
            //    pipeline.AddLast(new EchoServerHandler());
            //}));
            //IChannel boundChannel = await bootstrap.BindAsync(3000);
            //Console.ReadLine();
            //await boundChannel.CloseAsync();


            ctx.WriteAsync(message);
        }

        private void HandleArray(byte[] array, int offset, int length)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 批量读取中的最后一条消息已经读取完成
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelReadComplete(IChannelHandlerContext context)
        {
            context.Flush();
        }
        /// <summary>
        /// 发生异常
        /// </summary>
        /// <param name="context"></param>
        /// <param name="exception"></param>
        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            Console.WriteLine(exception);
            context.CloseAsync();
        }
    }
}
